const express = require('express');
const path = require('path');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const multer = require('multer');
const fs = require('fs');
const ffmpeg = require('fluent-ffmpeg');
const ffmpegPath = require('ffmpeg-static');
const ffprobePath = require('ffprobe-static').path;

// 设置fluent-ffmpeg使用项目内的ffmpeg
ffmpeg.setFfmpegPath(ffmpegPath);
ffmpeg.setFfprobePath(ffprobePath);
console.log('ffmpegPath', ffmpegPath);
console.log('ffprobePath:', ffprobePath);

const bodyParser = require('body-parser');
app.use(express.static('public'));
let uploadFiles = '';
let compressionOptions = {}
// 解析 application/x-www-form-urlencoded 类型的表单数据
app.use(bodyParser.urlencoded({ extended: false }));
//设置存储路径和文件名
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, __dirname + '/public/temp');
    },
    filename: function (req, file, cb) {
        file.originalname = Buffer.from(file.originalname, "latin1").toString('utf8');
        const originalname = file.originalname;
        const encodedFilename = encodeURIComponent(originalname); // 将文件名编码为合适的格式
        cb(null, Date.now() + '-' + originalname);
    }
})

const upload = multer({ storage: storage });

const outputPath = __dirname + '/public/output.mp4';
let outputFilePath = ''

io.on('connection', (socket) => {
    console.log('a user connected');
    socket.on('convert', (data) => {
        const uploadFile = uploadFiles;
        const resolvedPath = path.resolve(uploadFile.path);
        console.log('uploadFile.path:', uploadFile.path); // 添加调试日志
        console.log('resolvedPath:', resolvedPath); // 添加调试日志
        ffmpeg.ffprobe(String(uploadFile.path), (err, metadata) => {
            if (err) {
                console.error('Error while parsing metadata:', err);
            } else {
                //console.log('压缩前Metadata:', metadata);
            }
        });
        let command = ffmpeg(uploadFile.path)
        /* .outputOptions([
            '-r 24', // 设置帧率为 30fps
            '-b:v 3000k' // 设置视频比特率为 2Mbps
        ])
          // 添加滤镜，用于设置视频的编码格式为H.264
        .videoCodec('libx264') // 设置视频编码为 H.264
        .format('mp4') */
        if (compressionOptions.frameRate) {
            command = command.outputOptions('-r', compressionOptions.frameRate);
        }

        if (compressionOptions.bitrate) {
            command = command.outputOptions('-b:v', compressionOptions.bitrate);
        }

        if (compressionOptions.videoCodec) {
            command = command.videoCodec(compressionOptions.videoCodec);
        }

        if (compressionOptions.format) {
            var format
            var trans = {
                mp4: 'mp4',      // MPEG-4 Part 14 格式
                //'3gp': '3gp',    // 3GPP 文件格式
                m4a: 'mp4',      // M4A 是基于 MP4 的音频格式
                flv: 'flv',      // Flash Video 格式
                asf: 'asf',      // Advanced Systems Format (ASF) 容器，用于 WMV 和 WMA 文件
                m4v: 'mp4',      // 类似于 MP4 的视频格式，主要用于 iTunes 和 iPod
                avi: 'avi',      // Audio Video Interleaved 格式
                mov: 'mov',      // QuickTime File Format
                mpg: 'mpeg',     // MPEG-1 或 MPEG-2 视频流
                ts: 'mpegts',    // MPEG-TS (MPEG Transport Stream) 格式
                wmv: 'asf',      // Windows Media Video 使用 ASF 容器
                mkv: 'matroska', // Matroska 容器
                webm: 'webm',    // WebM 容器
                ogg: 'ogg'       // Ogg 容器
            };
            if (trans[compressionOptions.format]) {
                format = trans[compressionOptions.format];
            } else {
                format = compressionOptions.format;
            }
            command = command.format(format);
        }
        // 是否屏蔽音频
        if (compressionOptions.muteAudio) {
            command = command.noAudio();
        }
        //.size('256x144')
        command.output(outputFilePath)
        command.on('progress', (progress) => {
            socket.emit('progress', progress.percent);
        })
        command.on('end', () => {
            //删除临时文件
            fs.unlink(uploadFile.path, (err) => {
                if (err) throw err;
                console.log('删除临时文件成功');
            });
            ffmpeg.ffprobe(outputFilePath, (err, metadata) => {
                if (err) {
                    console.error('Error while parsing metadata:', err);
                } else {
                    console.log('压缩后Metadata:', metadata);
                    socket.emit('conversionComplete',metadata);
                }
            });
            
        })
        command.on('error', (err) => {
            console.error('Error while converting:', err);
        });
        command.run();
    });

    socket.on('disconnect', (err) => {
        console.log(err);
        console.log('A user disconnected');
    });
    // 监听错误事件
    socket.on('error', (error) => {
        console.error('Socket error:', error);
    });
});

app.post('/upload', upload.single('file'), (req, res) => {
    uploadFiles = req.file;
    compressionOptions = JSON.parse(req.body.compressionOptions);
    const filePath = uploadFiles.path;
    const fileExt = path.extname(filePath).slice(1);
    var output = `/output/${Date.now()}.${compressionOptions.format || fileExt}`;
    console.log(compressionOptions.format)
    outputFilePath = __dirname + `/public/${output}`;
    // 返回上传成功的响应
    res.send({
        code: 1000,
        output,
        name: uploadFiles.originalname
    });
});

server.listen(3001, () => {
    console.log('Server running on port 3001');
});